package org.gosilver.jerrymouse.connector;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.gosilver.jerrymouse.engine.HttpServletRequestImpl;
import org.gosilver.jerrymouse.engine.HttpServletResponseImpl;
import org.gosilver.jerrymouse.engine.ServletContextImpl;
import org.gosilver.jerrymouse.engine.filter.HelloFilter;
import org.gosilver.jerrymouse.engine.filter.LogFilter;
import org.gosilver.jerrymouse.engine.servlet.HelloServlet;
import org.gosilver.jerrymouse.engine.servlet.IndexServlet;
import org.gosilver.jerrymouse.engine.servlet.LoginServlet;
import org.gosilver.jerrymouse.engine.servlet.LogoutServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.ArrayList;

public class HttpConnector implements HttpHandler, AutoCloseable {

    final Logger logger = LoggerFactory.getLogger(getClass());

    final ServletContextImpl servletContext;
    final HttpServer httpServer;
    final Duration stopDelay = Duration.ofSeconds(5);

    public HttpConnector() throws IOException {
        this.servletContext = new ServletContextImpl();

        // 初始化过滤器
        ArrayList<Class<?>> filterList = new ArrayList<>();
//        filterList.add(HelloFilter.class);
//        filterList.add(LogFilter.class);
        this.servletContext.initFilters(filterList);

        // 初始化servlet
        ArrayList<Class<?>> list = new ArrayList<>();
        list.add(IndexServlet.class);
        list.add(LoginServlet.class);
        list.add(LogoutServlet.class);
        this.servletContext.initialize(list);
        // start http server:
        String host = "0.0.0.0";
        int port = 8080;
        this.httpServer = HttpServer.create(new InetSocketAddress(host, port), 0);
        this.httpServer.createContext( "/", this);
        this.httpServer.start();
        logger.info("jerrymouse http server started at {}:{}...", host, port);
    }

    @Override
    public void close() {
        this.httpServer.stop((int) this.stopDelay.getSeconds());
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        HttpExchangeAdapter adapter = new HttpExchangeAdapter(exchange);
        HttpServletResponseImpl response = new HttpServletResponseImpl(adapter);
        // 创建Request时，需要引用servletContext和response:
        HttpServletRequestImpl request = new HttpServletRequestImpl(this.servletContext, adapter, response);
        // process:
        try {
            this.servletContext.process(request, response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
